package com.example.light.system.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.light.system.config.IoTConfig;
import com.example.light.system.auth.IoTConsumer;
import com.example.light.system.auth.IoTMessage;
import com.example.light.system.auth.AESBase64Utils;

import com.example.light.system.service.impl.IDeviceService;
import io.netty.util.internal.StringUtil;
import org.apache.pulsar.client.api.MessageId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
public class IoTPulsarConsume {
    private static final Logger logger = LoggerFactory.getLogger(IoTPulsarConsume.class);

    // 剩余的静态属性和构造器...
    //TODO need to set iotAccessId 消费组ID
    private static  String iotAccessId="1gqmZkRvnYBsNYOTp517";
    //TODO need to set iotSecretKey 消费组KEY
    private static  String iotSecretKey="94979e6e26a64a73a2e8f85d612da53c";

    //TODO 订阅名称
    private static  String iotSubscriptionName="1gqmZkRvnYBsNYOTp517-sub";

    //实例化deviceService
    @Resource
    private IDeviceService iDeviceService;

    // 将原本在main方法中的逻辑放在一个非静态方法中
    public void start() throws Exception {
        // ...你原来main方法里的处理逻辑
        if (StringUtil.isNullOrEmpty(iotAccessId)) {
            logger.error("iotAccessId is null,please input iotAccessId");
            System.exit(1);
        }
        if (StringUtil.isNullOrEmpty(iotSecretKey)) {
            logger.error("iotSecretKey is null,please input iotSecretKey");
            System.exit(1);
        }
        if (StringUtil.isNullOrEmpty(iotSubscriptionName)) {
            logger.error("iotSubscriptionName is null,please input iotSubscriptionName");
            System.exit(1);
        }
        //TODO 建议收到消息后将消息转到中间件后立即ACK。避免消息量过大导致消息过期
        IoTConsumer iotConsumer = IoTConsumer.IOTConsumerBuilder.anIOTConsumer().brokerServerUrl(IoTConfig.brokerSSLServerUrl)
                .iotAccessId(iotAccessId)
                .iotSecretKey(iotSecretKey)
                .subscriptionName(iotSubscriptionName)
                .iotMessageListener(message -> {
                    MessageId msgId = message.getMessageId();
                    long publishTime = message.getPublishTime();
                    String payload = new String(message.getData());
                    IoTMessage iotMessage= JSONObject.parseObject(payload, IoTMessage.class);
                    String originalMsg= AESBase64Utils.decrypt(iotMessage.getData(),iotSecretKey.substring(8,24));
                    logger.info("IOT consume message======>>>>>>> messageId={}, publishTime={},  payload={}",
                            msgId, publishTime, payload);
                    logger.info("IOT originalMsg:{}",originalMsg);
                    JSONObject jsonObject = JSON.parseObject(originalMsg);
                    String msgType = jsonObject.get("msgType").toString();
                    JSONObject subData = jsonObject.getJSONObject("subData");
                    // 判断消息类型
                    if ("deviceOnline".equals(msgType)){
                        // 设备在线类型
                        // 将离线设备信息推送至设备状态转换接口
                        iDeviceService.changeDeviceStatus(subData,1);
                    } else if ("deviceOffline".equals(msgType)) {
                        // 设备离线类型
                        // 将离线设备信息推送至设备状态转换接口
                        iDeviceService.changeDeviceStatus(subData,0);
                    } else if ("thingProperty".equals(msgType)) {
                        // 环境数据类型
                        // 将环境数据推送至环境数据处理接口
                        iDeviceService.getEnvironmentData(subData);
                    }
                }).build();
        // 最后，启动iot消费者
        iotConsumer.run();
    }
}
